package com.lw.lost

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.lw.lost.activity.LoginActivity
import com.lw.lost.databinding.ActivityMainBinding
import com.lw.lost.fragments.*
import com.lw.lost.utils.PreferenceUtils

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 检查登录状态
        if (!PreferenceUtils.isLoggedIn(this)) {
            startActivity(Intent(this, LoginActivity::class.java))
            finish()
            return
        }

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 设置用户名
        supportActionBar?.title = "欢迎，${PreferenceUtils.getUserName(this)}"

        // 默认显示首页
        replaceFragment(HomeFragment())

        // 设置底部导航栏点击事件
        binding.bottomNavigation.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.nav_home -> replaceFragment(HomeFragment())
                R.id.nav_moments -> replaceFragment(MomentsFragment())
                R.id.nav_publish -> replaceFragment(PublishFragment())
                R.id.nav_friends -> replaceFragment(FriendsFragment())
                R.id.nav_profile -> replaceFragment(ProfileFragment())
            }
            true
        }
    }

    private fun replaceFragment(fragment: Fragment) {
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, fragment)
            .commit()
    }
}